import json
import re

import redis
from django.contrib.auth.hashers import make_password, check_password
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods

from django.core import signing
from choice.models import Collage
from utils.redis_pool import POOL
from .models import BasicUser
from utils.get_userId import gen_UserId


@csrf_exempt
@require_http_methods(['POST'])
def register(request):
    data = json.loads(request.body)
    user_info = data["userInfo"]
    # 获取用户输入的用户名。
    username = user_info.get('username')
    # 获取用户第一次输入的密码
    password = user_info.get('password')
    # 获取用户输入的第二次密码
    ag_password = user_info.get('ag_password')
    # 获取用户类型
    user_type = user_info.get('user_type')
    # 获取用户姓名
    real_name = user_info.get('real_name')
    # 获取用户邮箱
    email = user_info.get('email')
    # 获取用户选择院系
    collage_name = user_info.get('collage_name')
    if username == "" or password == "":
        return JsonResponse({'msg': '用户名或密码不能为空', 'status': 400})
    if len(username) < 6 or len(password) < 6:
        return JsonResponse({'msg': '用户名或密码长度不能小于6', 'status': 400})
    # 两次密码进行比对
    if password != ag_password:
        return JsonResponse({'msg': '两次密码输入不一致', 'status': 400})
    # 判断用户类型
    if user_type == "":
        return JsonResponse({'msg': '用户类型不能为空', 'status': 400})
    # 判断邮箱地址
    if email == "":
        return JsonResponse({'msg': '邮箱地址不能为空', 'status': 400})
    email_pattern = r'^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$'
    # 校验邮箱格式
    if re.match(email_pattern, email) is None:
        return JsonResponse({'msg': '邮箱格式不正确', 'status': 400})

    # 判断真实姓名
    if real_name == "":
        return JsonResponse({'msg': '姓名不能为空', 'status': 400})
    # 判断院系
    if collage_name == "":
        return JsonResponse({'msg': '所选院系不能为空', 'status': 400})
    user = BasicUser.objects.filter(user_name=username)
    if user:
        return JsonResponse({'msg': '该用户名已存在', 'status': 400})
    user_id = gen_UserId()
    collage = Collage.objects.filter(collage_name=collage_name)
    collage_id = collage.values()[0]["id"]
    try:
        user = BasicUser.objects.create(
            user_id=user_id,
            user_name=username,
            password=make_password(password),
            sex=0,
            email=email,
            collage_id=collage_id,
            user_type=user_type,
            real_name=real_name)
        user_info = {
            "user_id": user_id,
            "user_name": username,
            "email": email,
            "sex": 0,
            "real_name": real_name,
            "collage_name": collage_name,
            "user_type": user_type
        }
        token = signing.dumps(user_info)
        conn = redis.Redis(connection_pool=POOL)
        conn.set(user_id, token, ex=3600)
        res = JsonResponse(
            {'data': {"user_id": user_id, "user_type": user_type, "token": token}, 'status': 200})
        return res

    except Exception:
        return JsonResponse({'msg': '系统繁忙', 'status': 400})


@csrf_exempt
@require_http_methods(['POST'])
def login(request):
    data = json.loads(request.body)
    user_info = data["userInfo"]
    # 获取用户输入的用户名。
    username = user_info.get('username')
    # 获取用户第一次输入的密码
    password = user_info.get('password')
    # 获取用户类型
    user_type = user_info.get('user_type')
    if username == "" or password == "":
        return JsonResponse({'msg': '用户名或密码不能为空', 'status': 400})
    if len(username) < 6 or len(password) < 6:
        return JsonResponse({'msg': '用户名或密码长度不能小于6', 'status': 400})
    # 判断用户类型
    if user_type == "":
        return JsonResponse({'msg': '用户类型不能为空', 'status': 400})
    user = BasicUser.objects.filter(user_name=username)
    if user:
        user = user.values()[0]
        sha_password = user["password"].encode("utf-8").decode("latin1")
        if check_password(password, sha_password) is False:
            return JsonResponse({'msg': '密码错误', 'status': 400})
        collage_id = user["collage_id"]
        collage_name = Collage.objects.filter(id=collage_id)
        collage_name = collage_name.values()[0]["collage_name"]

        user_info = {
            "user_id": user["user_id"],
            "user_name": user["user_name"],
            "email": user["email"],
            "collage_name": collage_name,
            "real_name": user["real_name"],
            "sex": user["sex"],
            "user_type": user_type
        }
        token = signing.dumps(user_info)
        conn = redis.Redis(connection_pool=POOL)
        conn.set(user["user_id"], token, ex=3600)
        res = JsonResponse(
            {'data': {"user_id": user["user_id"], "user_type": user_type, "token": token}, 'status': 200})
        # res.set_cookie("userInfo", token, expires=datetime.now() + timedelta(days=14))
        return res
    else:
        return JsonResponse({'msg': '账号或密码有误', 'status': 400})


@csrf_exempt
def get_userInfo(request):
    token = request.META.get("HTTP_TOKEN")
    user_id = request.GET.get("user_id")
    if token == "" or token is None:
        return JsonResponse({'msg': '登录信息失效', 'status': 400})
    conn = redis.Redis(connection_pool=POOL)
    rel_token = conn.get(user_id).decode()
    if rel_token is None or rel_token != token:
        return JsonResponse({'msg': '登录信息失效', 'status': 400})
    conn.set(user_id, token, 3600)
    user_info = signing.loads(token)
    res = JsonResponse({'data': {"userInfo": user_info}, 'status': 200})
    return res
